from flask import Blueprint, jsonify, request, render_template, redirect, url_for, session, flash
from pymongo import MongoClient
from bson import ObjectId
import json
from datetime import datetime

# 修改蓝图名称和URL前缀
scratch_exercises_bp = Blueprint('scratch_exercises', __name__)

# MongoDB连接
client = MongoClient('mongodb://localhost:27017/')
db = client['scpy']
questions_collection = db['scratch_questions']
exams_collection = db['exams']  
submissions_collection = db['submissions']

@scratch_exercises_bp.route('/api/questions')
def get_questions():
    try:
        questions = list(questions_collection.find({}, {'_id': 0}))
        return jsonify(questions)
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@scratch_exercises_bp.route('/exam_list/<level>')
def exam_list(level):
    try:
        # 构建查询条件
        query = {'subject': 'scratch'}  # 只查询Scratch科目的试卷
        
        # 获取难度筛选参数
        difficulty = request.args.get('difficulty', 'all')
        if difficulty != 'all':
            query['difficulty'] = int(difficulty)
        
        # 从数据库获取试卷列表
        exams = list(exams_collection.find(query))
        
        # 处理试卷数据
        for exam in exams:
            exam['id'] = str(exam['_id'])
            del exam['_id']
            
        print(f"Query: {query}")  # 调试日志
        print(f"Found {len(exams)} exams")  # 调试日志
            
    except Exception as e:
        print(f"Error in exam_list: {str(e)}")  # 错误日志
        exams = []
    
    return render_template(
        'frontend/scratch_exam_list.html',
        exams=exams,
        level=level
    )

@scratch_exercises_bp.route('/exam/<level>/<exam_id>')
def start_exam(level, exam_id):
    try:
        # 从数据库获取试卷信息
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if exam:  # 确保试卷存在
            # 处理试卷数据
            exam['id'] = str(exam['_id'])
            del exam['_id']
            
            # 添加调试日志
            print(f"Found exam: {json.dumps(exam, default=str)}")
            
            # 渲染模板
            return render_template(
                'frontend/scratch_exam.html',
                exam=exam,
                level=level
            )
    except Exception as e:
        print(f"Error in start_exam: {str(e)}")  # 错误日志
    
    # 如果试卷不存在或发生错误，重定向到试卷列表
    return redirect(url_for('exercises.scratch_exercises.exam_list', level=level))

@scratch_exercises_bp.route('/exam/analysis/<exam_id>/<submission_id>')
def exam_analysis(exam_id, submission_id):
    try:
        # 获取试卷信息
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if not exam:
            flash('试卷不存在', 'error')
            return redirect(url_for('exercises.scratch_exercises.exam_list', level='all'))

        # 处理试卷数据
        exam['id'] = str(exam['_id'])
        del exam['_id']

        # 获取提交记录
        submission = submissions_collection.find_one({'_id': ObjectId(submission_id)})
        if not submission:
            flash('提交记录不存在', 'error')
            return redirect(url_for('exercises.scratch_exercises.exam_list', level='all'))

        # 处理提交记录数据
        submission['id'] = str(submission['_id'])
        del submission['_id']
        
        # 确保 submit_time 是 datetime 对象
        if isinstance(submission['submit_time'], str):
            submission['submit_time'] = datetime.strptime(submission['submit_time'], '%Y-%m-%d %H:%M:%S')

        # 渲染答题解析页面
        return render_template(
            'frontend/scratch_exam_analysis.html',
            exam=exam,
            submission=submission
        )

    except Exception as e:
        print(f"Error in exam_analysis: {str(e)}")  # 错误日志
        flash('查看解析时出错', 'error')
        return redirect(url_for('exercises.scratch_exercises.exam_list', level='all'))

@scratch_exercises_bp.route('/api/submit', methods=['POST'])
def submit_answers():
    try:
        data = request.get_json()
        answers = data.get('answers', [])
        exam_id = data.get('exam_id')
        
        # 从数据库获取试卷和正确答案
        exam = exams_collection.find_one({'_id': ObjectId(exam_id)})
        if not exam:
            return jsonify({
                'success': False,
                'error': '试卷不存在'
            })
            
        questions = exam.get('questions', [])
        total_questions = len(questions)
        correct_answers = 0
        
        # 检查答案
        for i, question in enumerate(questions):
            if i < len(answers):
                user_answer = answers[i]
                correct_answer = question.get('correct_answers', [])
                
                # 判断答案是否正确
                if question['type'] == 'multiple':
                    # 多选题：比较排序后的答案数组
                    if sorted(user_answer) == sorted(correct_answer):
                        correct_answers += 1
                elif question['type'] == 'single':
                    # 单选题：比较用户答案和正确答案的第一个值
                    if user_answer == correct_answer[0]:
                        correct_answers += 1
                else:  # boolean
                    # 判断题：直接比较布尔值
                    if user_answer == correct_answer[0]:
                        correct_answers += 1
        
        # 计算得分
        score = round((correct_answers / total_questions) * 100)
        
        # 保存提交记录
        submission = {
            'exam_id': exam_id,
            'exam_name': exam.get('name'),
            'subject': 'scratch',
            'user_answers': answers,
            'score': score,
            'correct_answers': correct_answers,
            'total_questions': total_questions,
            'submit_time': datetime.now(),
            'user_id': session.get('user_id', 'anonymous'),  # 如果用户未登录，使用 'anonymous'
            'username': session.get('username', '匿名用户'),
            'student_name': data.get('student_name', ''),
            'school': data.get('school', '')
        }
        
        # 将提交记录保存到数据库
        submission_result = submissions_collection.insert_one(submission)
        
        return jsonify({
            'success': True,
            'score': score,
            'correct_answers': correct_answers,
            'total_questions': total_questions,
            'submission_id': str(submission_result.inserted_id)
        })
        
    except Exception as e:
        print(f"Error in submit_answers: {str(e)}")  # 错误日志
        return jsonify({
            'success': False,
            'error': '提交答案时出错'
        })
